package com.zx._12_算法.剑指offer._2022;

/**
 * 请实现一个函数，把字符串 s 中的每个空格替换成"%20"。
 * https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/
 */
public class 替换空格 {

    /**
     * 1.利用jdk
     *
     * @param s
     * @return
     */
    public String replaceSpace1(String s) {
        return s.replace(" ", "%20");
    }

    /**
     * 2. 利用数组
     *
     * @param s
     * @return
     */
    public String replaceSpace2(String s) {
        char[] chars = new char[s.length() * 3];
        int idx = 0;

        int length = s.length();
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            if (c == ' ') {
                chars[idx++] = '%';
                chars[idx++] = '2';
                chars[idx++] = '0';
            } else {
                chars[idx++] = c;
            }

        }
        return new String(chars, 0, idx);
    }
}
